package server;

/**
 *@author Adam
 */

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.StringTokenizer;

public class SocketConnect extends Thread{

	public String my_serverHost;
	public int my_serverPort;
	public Server parent;
	boolean socketIsAlive = true;
	String RMIService = "";
	Socket toServer;
	PrintWriter out;

	public SocketConnect(String the_serverHost, int the_serverPort, Server myParent) {
		my_serverHost = the_serverHost;
		my_serverPort = the_serverPort;
		parent = myParent;
	}

	public void sendMessage(String a_message) {
		try {
			toServer = new Socket(my_serverHost, my_serverPort);
			out = new PrintWriter(toServer.getOutputStream(), true);
			out.println(a_message);
			BufferedReader in = new BufferedReader(new InputStreamReader(toServer.getInputStream()));
			String msg = in.readLine();
			System.out.println("Reply from device: " + msg);
			parse(msg);
			out.close();
			toServer.close();	
		} catch (IOException ioe) {
			ioe.printStackTrace();
		} catch (SecurityException se) {
			se.printStackTrace();
		}
		try{
		while (socketIsAlive == true){
			sleep(1000);
			Socket toServer = new Socket(my_serverHost, my_serverPort);
			PrintWriter out = new PrintWriter(toServer.getOutputStream(), true);
			out.println("alive");
		}
		} catch (Exception e){
			//e.printStackTrace();
			socketIsAlive = false;
			parent.deviceIsDead(my_serverHost, my_serverPort, RMIService);
			close();
		}
	}

	public void parse(String msg){
		StringTokenizer st = new StringTokenizer(msg, ",");
		String type = st.nextToken();
		this.RMIService = type;
		String address = st.nextToken();
		String size = st.nextToken();
		System.out.println("type = " + type + ", address = " + address + ", size = " + size);
		if (type.startsWith("storage")){
			parent.foundStorage(type,address);
		}
		if (type.startsWith("hifi")){
			parent.foundHifi(type,address,size);
		}
		if (type.startsWith("display")){
			parent.foundDisplay(type,address,size);
		}
	}
	
	public void close(){
		try{
		out.close();
		toServer.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void run(){
		sendMessage("<Helo>Details</Helo>");
	}
}

